<template lang="html">
  <div class="container">
    <div class="search-box">
      <input id="search" v-model="searchKey" type="search">
      <button @click="searchByHand">搜索</button>
      <div id="searchTip" class="tip-box" />
    </div>
    <div class="address-box">
      <div class="title">当前地址：</div>
      <input id="search" v-model="detailaddress" type="text" disabled>
      <button @click="close">确认</button>
      <div id="searchTip" class="tip-box" />
    </div>
    <!--
        amap-manager： 地图管理对象
        vid：地图容器节点的ID
        zooms： 地图显示的缩放级别范围，在PC上，默认范围[3,18]，取值范围[3-18]；在移动设备上，默认范围[3-19]，取值范围[3-19]
        center： 地图中心点坐标值
        plugin：地图使用的插件
        events： 事件
      -->
    <el-amap class="amap-box" :amap-manager="amapManager" :vid="'amap-vue'" :zoom="zoom" :plugin="plugin" :center="center" :events="events">
      <!-- 标记 -->
      <el-amap-marker v-for="(marker, index) in markers" :key="index" :position="marker" />
    </el-amap>
  </div>
</template>

<script>
import { AMapManager, lazyAMapApiLoaderInstance } from 'vue-amap'
// import AMap from 'AMap'
// import AMapUI from 'AMapUI'
const amapManager = new AMapManager()
export default {
  name: 'Elamapmarker',
  props: {
    selectedarea: {
      type: String,
      default: ''
    }
  },
  data() {
    const self = this
    return {
      address: null, // 详细地址
      detailaddress: '', // 顶部展示详细地址
      ladress: [], // 客户地址 省市区
      adcode: '',
      searchKey: '',
      amapManager,
      markers: [],
      searchOption: {
        city: '全国',
        citylimit: true
      },
      center: [121.329402, 31.228667],
      zoom: 17,
      lng: 0,
      lat: 0,
      loaded: false,
      events: {
        init() {
          lazyAMapApiLoaderInstance.load().then(() => {
            self.initSearch()
          })
        },
        // 点击获取地址的数据
        click(e) {
          self.markers = []
          const { lng, lat } = e.lnglat
          self.lng = lng
          self.lat = lat
          self.center = [lng, lat]
          self.markers.push([lng, lat])
          // 这里通过高德 SDK 完成。
          const geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              let arr = []
              let b = ''
              if (result && result.regeocode) {
                b = result.regeocode.addressComponent.province + result.regeocode.addressComponent.city + result.regeocode.addressComponent.district
                self.address = self.getArrDifference(b, result.regeocode.formattedAddress).join('')
                self.detailaddress = result.regeocode.formattedAddress
                self.adcode = result.regeocode.addressComponent.adcode
                arr = [result.regeocode.addressComponent.province, result.regeocode.addressComponent.city, result.regeocode.addressComponent.district]
                self.ladress = arr
                self.emitaddres()
                self.$nextTick()
              }
            }
          })
        }
      },
      // 一些工具插件
      plugin: [
        {
          pName: 'Geocoder',
          events: {
            init(o) {
              o.getAddress()
            }
          }
        },
        {
          // 定位
          pName: 'Geolocation',
          events: {
            init(o) {
              if (self.selectedarea == '') {
                // o是高德地图定位插件实例
                o.getCurrentPosition((status, result) => {
                  let arr = []
                  let b = ''
                  if (result && result.position) {
                    // 设置经度
                    self.lng = result.position.lng
                    // 设置维度
                    self.lat = result.position.lat
                    // 设置坐标
                    self.center = [self.lng, self.lat]
                    self.markers.push([self.lng, self.lat])
                    b = result.addressComponent.province + result.addressComponent.city + result.addressComponent.district
                    self.address = self.getArrDifference(b, result.formattedAddress).join('')
                    self.adcode = result.addressComponent.adcode
                    self.detailaddress = result.formattedAddress
                    arr = [result.addressComponent.province, result.addressComponent.city, result.addressComponent.district]
                    self.ladress = arr
                    self.emitaddres()
                    // load
                    self.loaded = true
                    // 页面渲染好后
                    self.$nextTick()
                  }
                })
              }
            }
          }
        },
        {
          // 工具栏
          pName: 'ToolBar',
          events: {
            init(instance) {
              // console.log(instance);
            }
          }
        },
        {
          // 鹰眼
          pName: 'OverView',
          events: {
            init(instance) {
              // console.log(instance);
            }
          }
        },
        {
          // 地图类型
          pName: 'MapType',
          defaultType: 0,
          events: {
            init(instance) {
              // console.log(instance);
            }
          }
        },
        {
          // 搜索
          pName: 'PlaceSearch',
          events: {
            init(instance) {
              // console.log(instance)
            }
          }
        }
      ]
    }
  },
  mounted() {
    this.getselectedarea()
  },
  methods: {
    initSearch() {
      const vm = this
      const map = this.amapManager.getMap()
      AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {
        var poiPicker = new PoiPicker({
          input: 'search',
          placeSearchOptions: {
            map: map,
            pageSize: 10
          },
          suggestContainer: 'searchTip',
          searchResultsContainer: 'searchTip'
        })
        vm.poiPicker = poiPicker
        vm.searchByHand() // 调用搜索按钮
        // 监听poi选中信息
        poiPicker.on('poiPicked', function(poiResult) {
          const source = poiResult.source
          const poi = poiResult.item
          console.log(poi)
          if (source !== 'search') {
            let a = poi.district + poi.name
            vm.searchKey = poi.district + poi.name
            poiPicker.searchByKeyword(a)
          } else {
            poiPicker.clearSearchResults()
            vm.markers = []
            let arr = []
            const lng = poi.location.lng
            const lat = poi.location.lat
            const address = poi.name
            vm.center = [lng, lat]
            vm.markers.push([lng, lat])
            vm.lng = lng
            vm.lat = lat
            vm.address = address
            vm.searchKey = address
            console.log(poi)
            vm.detailaddress = poi.pname + poi.cityname + poi.adname + poi.name
            vm.adcode = poi.adcode
            arr = [poi.pname, poi.cityname, poi.adname]
            vm.ladress = arr
            vm.emitaddres()
          }
        })
      })
    },
    searchByHand() {
      if (this.searchKey !== '') {
        console.log(this.searchKey)
        this.poiPicker.searchByKeyword(this.searchKey)
      }
    },
    emitaddres() {
      this.$emit('addrescode', this.markers, this.address, this.adcode, this.ladress)
    },

    // 取出两个数组的不同元素
    getArrDifference(arr1, arr2) {
      arr1 = arr1.split('')
      arr2 = arr2.split('')
      return arr2.splice(arr1.length, arr2.length)
    },
    // 完成按钮
    close() {
      this.$emit('close', false)
    },
    getselectedarea() {
      if (this.selectedarea != '') {
        this.searchKey = this.selectedarea
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 1200px;
  height: 800px;
  overflow: hidden;
}
.is-fullscreen {
  .container {
    width: 100%;
    height: 100%;
  }
}

.search-box {
  position: absolute;
  z-index: 5;
  width: 30%;
  left: 13%;
  top: 10px;
  height: 30px;
}
.search-box input {
  float: left;
  width: 80%;
  height: 100%;
  border: 1px solid #30ccc1;
  padding: 0 8px;
  outline: none;
}
.search-box button {
  float: left;
  width: 20%;
  height: 100%;
  background: #30ccc1;
  border: 1px solid #30ccc1;
  color: #fff;
  outline: none;
}
.address-box {
  position: absolute;
  z-index: 5;
  width: 35%;
  left: 55%;
  top: 10px;
  height: 30px;
}

.address-box .title {
  float: left;
  width: 17%;
  margin-top: 5px;
}

.address-box input {
  float: left;
  width: 67%;
  height: 100%;
  border: 1px solid #30ccc1;
  padding: 0 8px;
  outline: none;
  background-color: #fff;
}
.address-box button {
  float: left;
  width: 16%;
  height: 100%;
  background: #30ccc1;
  border: 1px solid #30ccc1;
  color: #fff;
  outline: none;
}
.tip-box {
  width: 100%;
  max-height: 260px;
  position: absolute;
  top: 30px;
  overflow-y: auto;
  background-color: #fff;
}
</style>
